<?php
namespace app\admin\model\blog;
use app\admin\model\BaseModel;

/**
 * 文章模型
 * Class Article
 * @package app\admin\model\blog
 */
class Article extends BaseModel {
    /*分类列表*/
    protected static $category;
    /*自动完成*/
    protected $auto = ['abstract'];

    /**
     * 自动提取摘要
     * @return string
     */
    public function setAbstractAttr() {
        $abstract = nl2br(mb_substr(strip_tags(\Parsedown::instance()->text($this->content)),0,150,"UTF-8"));
		if (mb_strpos($abstract,'<br />',null,'UTF-8') === 0){
            return mb_substr($abstract,6,150,'UTF-8');
        }
        return $abstract;
    }

    /**
     * 自动获取分类
     * @param $value
     * @param $data
     * @return string
     */
    public function getCateIdAttr($value,$data){
        $category = Category::get($value);
        return empty($category)?"未分类":$category->getData('name');
    }

    /**
     * 自动获取标签
     * @param $value
     * @param $data
     * @return string
     */
    public function getTagsAttr($value,$data){
        if (empty($value)){
            return '';
        }
        $tagname = Tags::where(['tag_id'=>['IN',$value]])->column('name','tag_id');
        $tags = explode(',',$value);
        $tagarr = [];
        foreach ($tags as $tag){
            $tagarr[] = $tagname[$tag];
        }
        return implode(',',$tagarr);
    }

    /**
     * 初始化
     */
    public static function init() {
        $logic = new \app\admin\logic\blog\Tags();
        static::event('before_insert',function($model) use ($logic){
            $model->tags = $logic->insertTag($model->getData('tags'));
        });
        static::event('after_insert',function($model) use ($logic){
			$tags = $model->getData('tags');
        	if (empty($tags)) return;
            $tags = explode(',',$tags);
            $article_id = $model->article_id;
            $save = [];
            foreach ($tags as $tag){
                $save[] = ['article_id'=>$article_id, 'tag_id'=>$tag];
            }
            db('TagsMap')->insertAll($save);
        });
        static::event('before_update',function($model) use ($logic){
            $model->tags = $logic->insertTag($model->getData('tags'));
        });
    }
}